<?php
 
class TCP
{
 
    private $server = null;
 
    public function __construct()
    {
        $this->server = new Swoole\Server('127.0.0.1', 9501);
 
        $this->server->set(array(
            'worker_num' => 4,     // 进程数
            'max_request' => 50,    // 每个进程最大接受请求数
        ));
 
        //监听连接进入事件。
        $this->server->on('Connect', [$this, 'onConnect']);
 
        //监听数据接收事件。
        $this->server->on('Receive', [$this, 'onReceive']);
 
        监听连接关闭事件。
        $this->server->on('Close', [$this, 'onClose']);
 
        //启动服务器
        $this->server->start();
    }
 
    public function onConnect($server, $fd)
    {
        echo "客户端id: {$fd}连接.\n";
    }
 
    public function onReceive($server, $fd, $reactor_id, $data)
    {
        $server->send($fd, "发送的数据: {$data}");
    }
 
    public function onClose($server, $fd)
    {
        echo "客户端id: {$fd}关闭.\n";
    }
 
}
 
 
new TCP();